//
//  APIManager.m
//  minidai
//
//  Created by 容贤郁 on 2017/5/21.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "APIManager.h"
#import "RSAUtil.h"

@implementation APIManager

+ (NSString *)sendRequestWithPath:(NSString *)path parameters:(NSDictionary *)params method:(XMHTTPMethodType)method onSuccess:(void (^)(ResponseModel *))success onFailure:(void (^)(NSError *))failure {
    
    NSString *requestIdentifier =  [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        
        request.api = path;
        request.httpMethod = method;
        request.parameters = params;
        request.responseSerializerType = kXMResponseSerializerJSON;
        request.retryCount = 1;
        
        [self addGeneralHeaders];
        
    } onSuccess:^(id  _Nullable responseObject) {
        
        NSLog(@"path: %@\nresponse: %@", path, responseObject);
        ResponseModel *response = [ResponseModel mj_objectWithKeyValues:responseObject];
        success(response);
    } onFailure:^(NSError * _Nullable error) {
        NSError *err = error.userInfo[@"NSUnderlyingError"];
        if (error.code == NSURLErrorBadServerResponse || error.code == 3840) {

            MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
            NSString *errorInfo = [NSString stringWithFormat:@"error_code=%zd", (long)err.code];
            if (user && user.user_code.length > 0) {
                errorInfo = [errorInfo stringByAppendingFormat:@",username=%@", user.user_code];
            }
            
            [SYExceptionRreport reportWithError:error keys:path value:errorInfo];
        }
        failure(error);
    }];
    
    return requestIdentifier;
}

+ (NSString *)sendRequestWithURL:(NSString *)url parameters:(NSDictionary *)params method:(XMHTTPMethodType)method onSuccess:(void (^)(ResponseModel *))success onFailure:(void (^)(NSError *))failure {
    NSString *requestIdentifier =  [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        
        if ([url containsString:@"http://"] || [url containsString:@"https://"]) {
            request.url = url;
        }else {
            request.api = url;
        }
//        request.url = url;
        request.httpMethod = method;
        request.parameters = params;
        request.responseSerializerType = kXMResponseSerializerJSON;
        request.retryCount = 1;
        
        [self addGeneralHeaders];
        
    } onSuccess:^(id  _Nullable responseObject) {
        NSLog(@"respone : %@", responseObject);
        ResponseModel *response = [ResponseModel mj_objectWithKeyValues:responseObject];
        success(response);
    } onFailure:^(NSError * _Nullable error) {
        NSError *err = error.userInfo[@"NSUnderlyingError"];
        if (error.code == NSURLErrorBadServerResponse || error.code == 3840) {
            MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
            NSString *errorInfo = [NSString stringWithFormat:@"error_code=%zd", (long)err.code];
            if (user && user.user_code.length > 0) {
                errorInfo = [errorInfo stringByAppendingFormat:@",username=%@", user.user_code];
            }
            
            [SYExceptionRreport reportWithError:error keys:url value:errorInfo];
        }
        NSLog(@"error : %@", error);
        failure(error);
    }];
    
    return requestIdentifier;
}


//下载文件
+ (NSString *)downloadWithUrl:(NSString *)url
                   onProgress:(void (^)(NSProgress *))progressBlock
                    onSuccess:(void (^)(ResponseModel *))success
                    onFailure:(void (^)(NSError *))failure
                     onFinish:(void (^)(id, NSError *))finish {
     kdeclare_weakself;
     NSString *requestIdentifier =  [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
         if ([url containsString:@"http://"] || [url containsString:@"https://"]) {
             request.url = url;
         }else {
             request.api = url;
         }
         request.downloadSavePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/"];
         request.requestType = kXMRequestDownload;
         [weakSelf addGeneralHeaders];
     }onProgress:^(NSProgress * _Nonnull progress) {
         if (progress) {
             progressBlock(progress);
         }
     } onSuccess:^(id  _Nullable responseObject) {
         if ([responseObject isKindOfClass:[NSData class]]) {
             NSError *transferError = nil;
             NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&transferError];
             if (transferError) {
                 NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                 NSLog(@"response: %@", responseStr);
             } else {
                 NSLog(@"response: %@", responseDict);
             }
         } else {
             NSLog(@"response: %@", responseObject);
         }
         ResponseModel *responseModel = [ResponseModel mj_objectWithKeyValues:responseObject];
         success(responseModel);
     } onFailure:^(NSError * _Nullable error) {
         failure(error);
     }onFinished:^(id  _Nullable responseObject, NSError * _Nullable error) {
         
         finish(responseObject, error);
     }];
    return requestIdentifier;
}

//图片上传

+ (NSString *)uploadWithUrl:(NSString *)url
                 parameters:(NSDictionary *)params
               uploadImages:(UIImage *)image
                  imageName:(NSString *)imageName
                 onProgress:(void (^)(NSProgress *))progressBlock
                  onSuccess:(void (^)(id))success
                  onFailure:(void (^)(NSError *))failure
                   onFinish:(void (^)(id, NSError *))finish {
    
    __weak typeof(self) weakSelf = self;
    
    NSString *identifier = [XMCenter sendRequest:^(XMRequest * _Nonnull request) {
        
        if ([url containsString:@"http://"] || [url containsString:@"https://"]) {
            request.url = url;
        } else {
            request.api = url;
        }
        request.httpMethod = kXMHTTPMethodPOST;
        request.responseSerializerType = kXMRequestSerializerJSON;
        request.requestType = kXMRequestUpload;
        request.parameters = params;
        
        //统一配置Header
        [weakSelf addGeneralHeaders];
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
        NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
        NSString *timestamp = [NSString stringWithFormat:@"%ld", (long)timeInterval];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", timestamp];
        [request addFormDataWithName:imageName fileName:fileName mimeType:@"image/jpeg" fileData:imageData];
        
    } onProgress:^(NSProgress * _Nonnull progress) {
        if (progress) {
            progressBlock(progress);
        }
        
    } onSuccess:^(id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSError *transferError = nil;
            NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&transferError];
            if (transferError) {
                NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"response: %@", responseStr);
            } else {
                NSLog(@"response: %@", responseDict);
            }
        } else {
            NSLog(@"response: %@", responseObject);
        }
        ResponseModel *responseModel = [ResponseModel mj_objectWithKeyValues:responseObject];
        success(responseModel);
        
    } onFailure:^(NSError * _Nullable error) {
        failure(error);
    } onFinished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        finish(responseObject, error);
    }];
    return identifier;
}

+ (void)addGeneralHeaders {
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    if (user && user.user_code.length > 0) {
        NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
        NSString *unreserved = @"";
        NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowed addCharactersInString:unreserved];
        
        NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
        [XMCenter setGeneralHeaderValue:encodeEncryText forField:@"USERCODE"];

    } else {
        [XMCenter setGeneralHeaderValue:nil forField:@"USERCODE"];
    }
    
    if (kDevice_iPad) {
        [XMCenter setGeneralHeaderValue:@"iPad" forField:@"WERTYUIOP"];
    } else {
        [XMCenter setGeneralHeaderValue:@"iPhone" forField:@"WERTYUIOP"];
    }
    
    [XMCenter setGeneralHeaderValue:kAPI_Version forField:@"mndversion"];
}



@end

@implementation ResponseModel

+ (NSString *)mj_replacedKeyFromPropertyName121:(NSString *)propertyName {
    return [propertyName mj_underlineFromCamel];
}

@end
